package com.jk.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jk.dao.ConcludeDao;
import com.jk.pojo.ConcludeBean;
import com.jk.pojo.RecordBean;
import com.jk.utils.ReturnMsgUtils;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.IdsQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ConcludeServcie
 * @Descripttion TODO
 * @Author DELL
 * @Date 2022/10/13 19:19
 * @Version 0.001
 */
@Service
public class ConcludeServcie {

    @Autowired
    private ConcludeDao concludeDao;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private RestHighLevelClient client;

    /**
     * @Author: binzi
     * @Description:查询签约
     * @Date: 2022/10/13 19:23
     * @Return: java.util.Map
     **/
    public Map findConclude(ConcludeBean bean) {
        String index = "conclude";
        GetIndexRequest indexRequest = new GetIndexRequest(index);
        boolean exists = false;
        try {//true
            exists = client.indices().exists(indexRequest, RequestOptions.DEFAULT);
            if (exists == false){//false
                QueryWrapper<ConcludeBean> recordBeanQueryWrapper = new QueryWrapper<ConcludeBean>();
                List<ConcludeBean> concludeBeans = concludeDao.selectList(recordBeanQueryWrapper);
                concludeBeans.forEach(ConcludeBean->{
                    elasticsearchRestTemplate.save(ConcludeBean);
                });
                return ReturnMsgUtils.returnMsg(200,"这是查询mqsql新增es",concludeBeans);
            }else {//true
                //先new 一个List 之后查出来的数据
                ArrayList<ConcludeBean> list = new ArrayList<>();

                //查询条件
                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                //姓名模糊查
                if (bean.getConclude_name() != null && bean.getConclude_name() != ""){
                    boolQueryBuilder.must(QueryBuilders.matchQuery("conclude_name",bean.getConclude_name()));
                }
                //时间区间查
                if (bean.getStaterDate() != null && bean.getStaterDate() != "" && bean.getEndDate() != null && bean.getEndDate() != ""){
                    boolQueryBuilder.must(QueryBuilders.rangeQuery("conclude_date").lte(bean.getEndDate()).gte(bean.getStaterDate()));
                }
                //签约机构精确查
                if (bean.getConclude_organization() != null){
                    boolQueryBuilder.must(QueryBuilders.termQuery("conclude_organization",bean.getConclude_organization()));
                }
                //签约状态查
                if (bean.getConclude_state() != null){
                    boolQueryBuilder.must(QueryBuilders.termQuery("conclude_state",bean.getConclude_state()));
                }
                //服务包精确查
                if (bean.getConclude_server() != null){
                    boolQueryBuilder.must(QueryBuilders.termQuery("conclude_server",bean.getConclude_server()));
                }
                //医生团队精确查
                if (bean.getConclude_doctor_team() != null){
                    boolQueryBuilder.must(QueryBuilders.termQuery("conclude_doctor_team",bean.getConclude_doctor_team()));
                }

                //高亮
                HighlightBuilder highlightBuilder = new HighlightBuilder();
                //实体类要高亮的value字段
                highlightBuilder.field("conclude_name");
                highlightBuilder.preTags("<font color='red'>");
                highlightBuilder.postTags("</font>");

                NativeSearchQuery query = new NativeSearchQueryBuilder()
                        .withQuery(boolQueryBuilder)
                        .withHighlightBuilder(highlightBuilder)
                        .build();

                SearchHits<ConcludeBean> search = elasticsearchRestTemplate.search(query, ConcludeBean.class);

                //获取查询的 hit
                List<SearchHit<ConcludeBean>> searchHits = search.getSearchHits();

                //循环获取到的hit
                searchHits.forEach(hit->{

                    //获取高亮的内容
                    Map<String, List<String>> highlightFields = hit.getHighlightFields();
                    //判断高亮的字段是否有值
                    hit.getContent().setConclude_name(highlightFields.get("conclude_name") == null ? hit.getContent().getConclude_name():highlightFields.get("conclude_name").get(0));
                    list.add(hit.getContent());

                });
                return ReturnMsgUtils.returnMsg(200,"这是es中的数据",list);
            }
        } catch (IOException  e) {
            e.printStackTrace();
            return ReturnMsgUtils.returnMsg(500,"服务器异常",null);
        }
    }

    /**
     * @Author: binzi
     * @Description:新增MySql数据库同步到es中
     * @Date: 2022/10/14 10:12
     * @Return: boolean
     **/
    public void addConclude(ConcludeBean concludeBean) {
        concludeDao.insert(concludeBean);
        QueryWrapper<ConcludeBean> queryWrapper = new QueryWrapper<>();
        List<ConcludeBean> concludeBeans = concludeDao.selectList(queryWrapper);
        concludeBeans.forEach(ConcludeBean->{
            elasticsearchRestTemplate.save(ConcludeBean);
        });

    }

    /**
     * @Author: binzi
     * @Description:根据Id（编号）查询数据
     * @Date: 2022/10/14 10:23
     * @Return: com.jk.pojo.ConcludeBean
     **/
    public ConcludeBean findConcludeById(Integer conclude_id) {
        //索引名称
        String index = "conclude";
        GetIndexRequest indexRequest = new GetIndexRequest(index);
        boolean exists = false;
        //判断es中索引是否存在 存在true,不存在false
        try {//true
            exists = client.indices().exists(indexRequest, RequestOptions.DEFAULT);
            if (exists == false){
                return concludeDao.selectById(conclude_id);
            }else {
                IdsQueryBuilder ids = QueryBuilders.idsQuery();
                ids.addIds(conclude_id.toString());
                NativeSearchQuery build = new NativeSearchQueryBuilder()
                        .withQuery(ids)
                        .build();
                SearchHit<ConcludeBean> concludeBeanSearchHit = elasticsearchRestTemplate.searchOne(build, ConcludeBean.class);
                if (concludeBeanSearchHit != null){
                    ConcludeBean content = concludeBeanSearchHit.getContent();
                    return content;
                }else {
                    return null;
                }
            }
        } catch (IOException e) {//false
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @Author: binzi
     * @Description:根据Id删除对应的数据
     * @Date: 2022/10/14 10:33
     * @Return: boolean
     **/
    public boolean delConcludeById(Integer conclude_id) {
        try {
            concludeDao.deleteById(conclude_id);
            elasticsearchRestTemplate.delete(conclude_id.toString(), IndexCoordinates.of("conclude"));
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * @Author: binzi
     * @Description:查询当前时间的前七点数据
     * @Date: 2022/10/17 19:37
     * @Return: java.util.List<com.jk.pojo.ConcludeBean>
     **/
    public Map findConcludeByDateWeed() {
        List<Integer> list = concludeDao.findConcludeByDateWeed();
        return  ReturnMsgUtils.returnMsg(200,"1111",list);
    }

    /**
     * @Author: binzi
     * @Description:待处理服务量
     * @Date: 2022/10/18 10:29
     * @Return: java.util.Map
     **/
    public Integer findConcludeByStateCountTwo() {
        return concludeDao.findConcludeByStateCountTwo();
    }
}
